import Cookies from 'js-cookie'
import {
  getNation,
  getMarriage,
  getPolitic,
  getDormitory,
  getPosition,
  getDept,
  getEducation
} from '@/api/basic'
const state = {
  sidebar: {
    opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
    withoutAnimation: false
  },
  device: 'desktop',
  size: Cookies.get('size') || 'medium'
  // foundation: {}
}

const mutations = {
  // 把获取的数据加入缓存
  setFoundation: (state, name, arr) => {
    state[name] = arr
  },
  TOGGLE_SIDEBAR: state => {
    state.sidebar.opened = !state.sidebar.opened
    state.sidebar.withoutAnimation = false
    if (state.sidebar.opened) {
      Cookies.set('sidebarStatus', 1)
    } else {
      Cookies.set('sidebarStatus', 0)
    }
  },
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    Cookies.set('sidebarStatus', 0)
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  },
  SET_SIZE: (state, size) => {
    state.size = size
    Cookies.set('size', size)
  }
}

const actions = {
  // 异步获取数据
  async getFoundation({
    commit
  }, name) {
    const post = {
      education_id: getEducation, // 学历查询
      nation_id: getNation, // 民族
      marital_id: getMarriage, // /婚姻
      politic_id: getPolitic, // 政治面貌
      department_id: getDept, // 获取部门
      position_id: getPosition, // 获取职位
      room_id: getDormitory // 宿舍
    }
    try {
      if (name) {
        return post[name]().then(res => {
          commit('setFoundation', name, res.data)
          return res.data
        })
      } else {
        Object.keys(post).forEach(async (elm) => {
          const {
            data
          } = await post[elm]()
          commit('setFoundation', elm, data)
        })
      }
    } catch (error) {

    }
  },
  toggleSideBar({
    commit
  }) {
    commit('TOGGLE_SIDEBAR')
  },
  closeSideBar({
    commit
  }, {
    withoutAnimation
  }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  toggleDevice({
    commit
  }, device) {
    commit('TOGGLE_DEVICE', device)
  },
  setSize({
    commit
  }, size) {
    commit('SET_SIZE', size)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
